package stream.reduce;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

//归纳也称缩减 就是把一个流缩减成一个值，能实现对集合求和求乘积求最值的操作
//主要方法  reduce(Integer::XX方法)
public class demo1 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
        //求和方式1
        Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
        //求和方式2
        Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
        //求和方式3
        Integer sum3 = list.stream().reduce(0, Integer::sum);

        //求乘积
        Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

        //求最大值公式
        Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
        //求最大值的求法
        Integer max2 = list.stream().reduce(1, Integer::max);

        System.out.println("list求和：" + sum.get() + "," + sum2.get() + "," + sum3);
        System.out.println("list求积：" + product.get());
        System.out.println("list求max：" + max.get() + "," + max2);

    }
}
